//
// Created by 28365 on 2025/3/10.
//

#ifndef ODUPDATERSDK_THREADPOOL_H
#define ODUPDATERSDK_THREADPOOL_H

#include <vector>
#include <thread>
#include <queue>
#include <functional>
#include <mutex>
#include <condition_variable>
#include <future>
#include "ThreadFactory.h"

using namespace std;

class ThreadPool {

private:
    // 工作线程
    vector<thread*> workers;
    // 任务队列
    queue<function<void()>> tasks;
    //线程创建工厂
    ThreadFactory *threadFactory;

    // 同步机制
    mutex queue_mutex;
    condition_variable condition;
    condition_variable queue_condition;

    size_t coreSize;
    size_t queueSize;

    bool stop = false;

    //启动新消费者线程
    void startTask();

public:
    /**
     * 创建线程
     * @param _coreSize 工作线程数量
     * @param _queueSize 队列大小
     */
    explicit ThreadPool(size_t _coreSize, size_t _queueSize);

    /**
     * 队列满时阻塞等待
     * @param runnable
     */
    void execute(function<void()> &&runnable);

    //打上停止标签，不接受新任务，但队列内的任务全部运行完成时停止
    void shutdown();

    //打上停止标签，不接受新任务，同时丢弃队列中的所有任务,待当前运行的线程结束后停止
    void shutdownAndDiscard();

    void await();

    size_t getWorkerSize();

    [[nodiscard]] size_t getCoreSize() const;

    void setCoreSize(size_t coreSize);

    virtual ~ThreadPool();
};

#endif //ODUPDATERSDK_THREADPOOL_H
